//引入登录.退出登录,获取用户信息的接口
import { login, logout, getInfo } from '@/api/user'
//引入获取token,设置token,删除token的函数
import { getToken, setToken, removeToken } from '@/utils/auth'
//路由模块中重置路由的方法
//任意路由,重置路由的方法,异步路由,常量路由
import { anyRoutes, resetRouter, asyncRoutes, constantRoutes } from '@/router';
import router from '@/router';
import cloneDeep from 'lodash/cloneDeep'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    //存储用户头像
    avatar: '',
    //服务器返回的菜单信息(根据不同角色,返回的标记信息,数组里的元素是字符串)
    routes: [],
    //角色信息
    roles: [],
    //按钮权限信息
    buttons: [],
    //对比之后的异步路由
    resultAsyncRoutes: [],
    //用户最终要展示的全部路由
    resultAllRoutes: []
  }
}

const state = getDefaultState()

const mutations = {
  // 重置state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //存储用户信息
  SET_USERINFO: (state, userInfo) => {
    //用户名
    state.name = userInfo.name;
    //用户头像
    state.avatar = userInfo.avatar;
    //菜单权限标记
    state.routes = userInfo.routes;
    //按钮权限标记
    state.buttons = userInfo.buttons;
    //角色
    state.roles = userInfo.roles;
  },
  //最终计算出的异步路由
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
    //仓库中保存当前的异步路由
    state.resultAsyncRoutes = asyncRoutes;
    //计算出登录的角色一共要展示出哪里路由,数组合并,把常量路由于过滤出的异步路由和任意路由合并
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)

    //给路由器添加新的路由
    router.addRoutes(state.resultAllRoutes)
  }
}

//方法:用于让两个数组对比,对比当前的用户一共要显示出哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {

  //要把过滤出的数组返回
  return asyncRoutes.filter(item => {

    //要是routes总路由中有这个数组中的名字再过滤出来 
    if (routes.indexOf(item.name) != -1) {
      //如果数组里还有多级路由,要递归出来
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes)

      }
      return true
    }
  })
}

const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    //用async与await
    let result = await login({ username: username.trim(), password: password })
    if (result.code == 20000) {
      //成功了则发请求,再把返回的token存在cookie中
      commit('SET_TOKEN', result.data.token)

      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }

    /* return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    }) */
  },

  // 获取了用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        //存储用户信息
        commit('SET_USERINFO', data)
        //存储要展示的路由
        commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(cloneDeep(asyncRoutes), data.routes));

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

